package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;

public class ReflectDemo9 {
    public static void main(String[] args) throws Exception {
        Class cls = ReflectDemo9.class;
        String packname = cls.getPackage().getName();
        File dir = new File(Test3.class.getResource(".").toURI());
        File[] subs = dir.listFiles(file -> file.getName().endsWith(".class"));
        for (File sub : subs) {
            String filename = sub.getName();
            String classname = filename.substring(0, filename.indexOf("."));
            classname = packname + "." + classname;
            Class c = Class.forName(classname);
            if (c.isAnnotationPresent(AutoRunClass.class)) {
                Object o = c.newInstance();
                System.out.println(o);
                Method[] methods = c.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    if(methods[i].isAnnotationPresent(AutoRunMethod.class) && methods[i].getModifiers() == Modifier.PUBLIC) {
                        System.out.println(methods[i].getName());
                        Method method = c.getDeclaredMethod(methods[i].getName());
                        method.invoke(o);
                    }
                }
            }
        }
    }
}
